//
//  KSWebViewController.m
//  BasketBallLeagues
//
//  Created by kenshin on 21/05/2017.
//  Copyright © 2017 kenshin. All rights reserved.
//

#import "KSWebViewController.h"
#import <WebViewJavascriptBridge/WebViewJavascriptBridge.h>
#import "CYShareSheetView.h"
#import "BLUMSocialManager.h"
#import "BLCommentInputView.h"
//#import "BLApplyViewController.h"

@interface KSWebViewController ()
<
UIWebViewDelegate
//ShareViewDelegate,
//JZWebServiceDelegate,
//IDMPhotoBrowserDelegate
>


@property(nonatomic,strong)UIView* naviBar;
@property(nonatomic,strong)UILabel* titleLabel;
@property(nonatomic,strong)UILabel* enTitleLabel;
@property(nonatomic,strong)UIView* btmLine;
@property(nonatomic,strong)UIActivityIndicatorView* activityIndicatorView;
@property(nonatomic,strong)UIView* loadFailView;
@property(nonatomic,strong)UIImageView* loadFailIcon;

@property(nonatomic,strong)UILabel* loadFailDescLabel;
@property (nonatomic, strong) UIButton *applyButton; //报名按钮

/**
 *  关闭按钮
 */
@property (nonatomic, strong) UIButton *btnClose;
@property (nonatomic, strong) UIButton *btnShare;

@property (nonatomic,strong)WebViewJavascriptBridge* bridge;
//@property (nonatomic, strong) JZWebService *webService;


@property (nonatomic,strong) NSDictionary *loginData;


@property (nonatomic, strong) CYShareSheetView *shareSheetView;


@end

@implementation KSWebViewController

+ (KSWebViewController *)pushWithURL:(NSString *)url title:(NSString *)title navController:(UINavigationController *)nav shareinfo:(NSDictionary *)shareinfo {
    KSWebViewController *controller = [[KSWebViewController alloc] initWithURL:[NSURL URLWithString:url]];
    controller.title = title;
    if ([title length] > 0) {
        controller.showPageTitles = NO;
    }
    controller.loadingBarTintColor = [UIColor orangeColor];
    controller.showUrlWhileLoading = NO;
    controller.showLoadingBar = YES;
    //    controller.navigationButtonsHidden = YES;
    [controller.navigationController setToolbarHidden:YES animated:NO];
    //    controller.navigationController.navigationBarHidden = YES;
    [nav pushViewController:controller animated:YES];
    
    return controller;
}

/*电池显示*/
-(BOOL)prefersStatusBarHidden{
    return NO;
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

-(BOOL)modalPresentationCapturesStatusBarAppearance{
    return YES;//模态隐藏状态栏
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    [self.navigationController setNavigationBarHidden:YES animated:NO];
    //    NSLog(@"%s,%@",__func__,self);
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
//    [self.navigationController setNavigationBarHidden:YES animated:NO];
    //    NSLog(@"%s,%@",__func__,self);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isHideNav = YES;
//    self.navigationController.navigationBarHidden = YES;
    self.navigationButtonsHidden = YES; //隐藏TOWebViewController默认的底部按钮
//    self.defaultTopNavigationButtonsHidden = YES; //隐藏TOWebViewController默认的顶部导航按钮
    
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    
        [self setupNavUI];
//    });
    [self setupWebView];
    [self setupLoadFailView];
    
    self.activityIndicatorView = [[UIActivityIndicatorView alloc] init];
    self.activityIndicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    [self.view addSubview:self.activityIndicatorView];
    [self.activityIndicatorView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view);
    }];
    [self.activityIndicatorView startAnimating];
    
    CGRect webViewFrame = self.webView.frame;
    webViewFrame.size.height -= 48;
    self.webView.frame = webViewFrame;
}

-(void)setupLoadFailView{
    self.loadFailView = [[UIView alloc]initWithFrame:CGRectMake(self.view.centerX - 85, self.view.centerY - 90, 170, 180)];
    self.loadFailView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.loadFailView];
    self.loadFailView.hidden = YES;
    
    self.loadFailIcon = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 134, 134)];
    [self.loadFailView addSubview:self.loadFailIcon];
    self.loadFailIcon.centerX = self.loadFailView.width / 2;
    
    self.loadFailDescLabel  = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.loadFailView.width, 35)];
    self.loadFailDescLabel.text = @"您的网络歇菜了......换个更快的网络试试吧!点击刷新";
    self.loadFailDescLabel.textAlignment = NSTextAlignmentCenter;
    self.loadFailDescLabel.numberOfLines = 2;
    self.loadFailDescLabel.font = [UIFont systemFontOfSize:13];
    [self.loadFailView addSubview:self.loadFailDescLabel];
    self.loadFailDescLabel.bottom = self.loadFailView.height;
    
    UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(refreshActivity:)];
    [self.loadFailView addGestureRecognizer:tap];
}

-(void)refreshActivity:(UITapGestureRecognizer*)tap {
    self.loadFailView.hidden = YES;
    [self.webView loadRequest:[NSURLRequest requestWithURL:self.url]];
    [self.activityIndicatorView startAnimating];
}

#pragma mark - UI Setup

- (BOOL)webViewCanGoBack
{
    return self.webView.canGoBack;
}

- (void)webViewGoBack
{
    [self.webView goBack];
}

-(void)setupWebView{
    //调整webview位置
    if (self.isHideNav) {
        self.naviBar.hidden = YES;
    }else{
        self.webView.top = mNavBarHeight;
        self.webView.height -= mNavBarHeight;
    }
    self.webView.delegate = self;
    //    self.webView.hidden = YES;
    self.webView.backgroundColor = [UIColor jc_colorWithHexString:@"0xf6f6f6"];
    [WebViewJavascriptBridge enableLogging];
    
//    if (!self.webService) {
//        self.bridge = [WebViewJavascriptBridge bridgeForWebView:self.webView webViewDelegate:self handler:^(id data, WVJBResponseCallback responseCallback) {
//            NSLog(@"ObjC received message from JS: %@", data);
//            responseCallback(@"Response for message from ObjC");
//        }];
//        
//        self.webService = [[JZWebService alloc] initWithBridge:self.bridge navController:self.navigationController articleID:0 delegate:self];
//    }
//    
//    [self.webService registerAll];
    
}


- (void)resetTitle:(NSString *)title
{
//    [super resetTitle:title];
    
    self.titleLabel.text = title;
}

- (void)refreshButtonsState
{
//    [super refreshButtonsState];
    
    self.btnClose.hidden = ![self webViewCanGoBack];
}


- (void)ks_rightButtonPressed:(id)sender
{
    [self btnShareClicked:sender];
}

-(void)setupNavUI {
    [self ks_setupLeftBackBarButtonItem];
//    self.applicationLeftBarButtonItems = @[self.navigationItem.leftBarButtonItem];
    if (self.isShareBtnShow) {
        self.btnShare = [self ks_setupRightButtonItemWithTitle:nil image:[UIImage imageNamed:@"icon_share"] highLightedImage:[UIImage imageNamed:@"icon_share"]];
    }
//    self.loadCompletedApplicationBarButtonItems = @[self.navigationItem.rightBarButtonItem];
    
//    self.naviBar = [[UIView alloc]initWithFrame:CGRectMake(0, 0, mScreenWidth, mNavBarHeight+20)];
//    self.naviBar.backgroundColor = [BLColorConfig mainColor];
//    [self.view addSubview:self.naviBar];
//    
//    UIButton * btnBack = [[UIButton alloc]initWithFrame:CGRectMake(0,0,mNavBarHeight, 20)];
//    btnBack.centerY = self.naviBar.centerY + 10;
//    [btnBack setImage:[UIImage imageNamed:@"navigation_back_icon"] forState:UIControlStateNormal];
//    [btnBack addTarget:self action:@selector(btnBackClicked:) forControlEvents:UIControlEventTouchUpInside];
//    [self.naviBar addSubview:btnBack];
//    
//    UIButton* tmpBtnShare = [[UIButton alloc]initWithFrame:CGRectMake(CGRectGetWidth(self.naviBar.bounds)-30-10,20,30, 30)];
//    tmpBtnShare.centerY = btnBack.centerY;
//    [tmpBtnShare setImage:[UIImage imageNamed:@"icon_share"] forState:UIControlStateNormal];
//    [tmpBtnShare addTarget:self action:@selector(btnShareClicked:) forControlEvents:UIControlEventTouchUpInside];
//    [self.naviBar addSubview:tmpBtnShare];
//    self.btnShare = tmpBtnShare;
//    
//    self.titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(btnBack.frame), 0, 200, 20)];
//    self.titleLabel.text = @"详情";
//    self.titleLabel.font = [UIFont systemFontOfSize:16];
//    self.titleLabel.centerY = btnBack.centerY;
//    [self.naviBar addSubview:self.titleLabel];
//    self.titleLabel.centerY = btnBack.centerY;
//    
//    self.btmLine = [[UIView alloc]initWithFrame:CGRectMake(0, mNavBarHeight+20-1, mScreenWidth, 1)];
//    [self.naviBar addSubview:self.btmLine];
    
    
//    UIButton *tmpBtnClose = [[UIButton alloc] initWithFrame:CGRectMake(40,20,mNavBarHeight, mNavBarHeight)];
//    [tmpBtnClose setImage:[[UIImage imageNamed:@"icon-close"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
//    tmpBtnClose.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
//    [tmpBtnClose addTarget:self action:@selector(btnCloseClicked:) forControlEvents:UIControlEventTouchUpInside];
//    [self.naviBar addSubview:tmpBtnClose];
//    tmpBtnClose.hidden = YES;
//    self.btnClose = tmpBtnClose;
}

#pragma mark - WebView


- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    return [super webView:webView shouldStartLoadWithRequest:request navigationType:navigationType];
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [super webViewDidStartLoad:webView];
}

-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    //    NSLog(@"%s",__func__);
    if ([error code] != NSURLErrorCancelled) { //如果是-999取消，则不作为web加载失败处理
        [super webView:webView didFailLoadWithError:error];
        self.loadFailView.hidden = NO;
        [self.activityIndicatorView stopAnimating];
    }
    //    self.webView.hidden = YES;
}

-(void)webViewDidFinishLoad:(UIWebView *)webView {
    [super webViewDidFinishLoad:webView];
    //    NSLog(@"%s",__func__);
    self.loadFailView.hidden = YES;
    [self.activityIndicatorView stopAnimating];
    
//    //切换夜间模式
//    int readMode = [ThemeManager isNightMode] ? 1 : 0;
//    [_bridge callHandler:@"readMode" data:@{@"readtype":@(readMode)} responseCallback:^(id responseData) {
//        NSLog(@"addFooter got response! %@", responseData);
//    }];
    
//    //延迟一点调整webview，更平滑
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        //        self.webView.hidden = NO;
//        //        NSLog(@"dispatch_after(),callback");
//        if (self.callBack) {
//            self.callBack();
//        }
//        
//    });
    
    
}

#pragma mark - Actions

- (void)btnBackClicked:(UIButton*)btnBack{
    if ([self webViewCanGoBack]) {
        [self webViewGoBack];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)btnCloseClicked:(UIButton *)btn
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)showShareBtn:(BOOL)show {
    self.btnShare.hidden = !show;
}

- (void)btnShareClicked:(id)sender{

    [self autoFetchShareDataIfNeeded];
    
    [self.shareSheetView platformClicked:^(int platform) {
        NSLog(@"----%d",platform);
        [BLUMSocialManager shareWebPageToPlatformType:platform info:self.shareinfo];
    }];
    [self.shareSheetView show];
}

//- (void)toShare:(NSInteger)sharePlatform
//{
//    
//}

- (void)doShare:(NSInteger)sharePlatform shareImageURL:(NSString *)imageURL
{
    [self autoFetchShareDataIfNeeded];
    //TODO:share
}

#pragma mark - share

//- (void)showShareView:(NSInteger)sharePlatform{
//    [self toShare:sharePlatform];
//}

- (void)autoFetchShareDataIfNeeded
{
    if (!self.shareinfo) {
        
        //        NSString *script = [NSString stringWithFormat:
        //                            @"var div = document.createElement('div');"
        //                            "div.style.marginTop=\"%.fpx\";"
        //                            "document.body.appendChild(div);",
        //                            height];
        
        //            NSString *script = @"document.getElementsByTagName('img')[0].src";
        //            NSString *pic = [self.webView stringByEvaluatingJavaScriptFromString:script];
        NSString *title = [self.webView stringByEvaluatingJavaScriptFromString:@"document.title"];
        if ([self.title length] == 0) {
            self.title = title;
        }
        self.shareinfo = [@{@"title":title,@"subtitle":title,@"pic":@"",@"shareurl":self.url.absoluteString} mutableCopy];
    }
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskPortrait;
}

#pragma mark - lazyload
- (CYShareSheetView *)shareSheetView {
    if (!_shareSheetView) {
        _shareSheetView = [[CYShareSheetView alloc] init];
    }
    return _shareSheetView;
}

@end
